package cn.wolfcode.luowowo.website.util;

/**
 * @author 猫教授
 * @date 2019/8/8 21:16
 */

import cn.wolfcode.luowowo.cache.service.IUesrInfoCacheService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 此工具类是用来重写参数解析器,在贴有@UserParam这个注解的用户对象参数上,自动注入当前的登录用户对象
 */
@Component
public class UserParamResolve implements HandlerMethodArgumentResolver {

    @Reference
    private IUesrInfoCacheService redisCacheService;
    /**
     * 这里的方法是对方法参数的进行匹配也就是满足了这个条件的话就会调用下面的这个参数注入方法
     * @param parameter 方法封装的参数对象,这里的参数指的是每一个参数,都会独自进行判断
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果参数是会员对象类型并且贴有这个注解参数,那么就输出true,调用下面的这个注入参数
        return parameter.getParameterType()== UserInfo.class&&parameter.hasParameterAnnotation(UserParam.class);
    }

    /**
     * 执行参数注入
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //首先吸纳
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = CookieUtil.getToken(request);
        return redisCacheService.getUserInfo(token);
    }
}
